import config
import linshi_list
from config import ENGINES
from flask import Blueprint, render_template, redirect
from flask import request, current_app
from .forms import RegisterForm
from models import IconWeb
from search_icon import get_favicon_url

navigation_blueprint = Blueprint('navigation', __name__, url_prefix='/')


@navigation_blueprint.route('/search', methods=['GET'])
def search():
    if request.method == 'GET' and request.args:
        form = RegisterForm(request.args)
        if form.validate():
            engine = form.engine.data
            wd = form.wd.data
            # 默认 engine 不是预期的值，重定向回首页
            next_page = '/'
            if 0 < engine <= len(ENGINES) and wd:
                search_web = ENGINES[engine - 1][2]
                next_page = search_web + wd if search_web else ENGINES[0][2] + wd
            return redirect(next_page)
        else:
            print(form.errors)
            return redirect('/')


@navigation_blueprint.route('/')
def index():
    form = RegisterForm()
    icowebs = linshi_list.web_icons

    for web_icon in icowebs:
        web_icon['icon'] = get_favicon_url(web_icon['address'])

    icowebs = icowebs
    # print(icowebs)
    # todo 这里后面要添加如果登录那么获取不一样的数据
    # iconweb = IconWeb.query.all()
    return render_template('index.html', form=form, icowebs=icowebs)



